﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AISservice.Common
{
    public class RemoteMiddleware
    {
        private RequestDelegate _next;
        private const string RequestHeader = "token";
        private const string ResponseHeader = "Application";

        public RemoteMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, IApplicationLifetime lifetime)
        {
            if (context.Request.Headers[RequestHeader].FirstOrDefault() == "Y")
            {
                context.Response.Headers.Add(ResponseHeader, "Yes");
                lifetime.StopApplication();
            }
            else if (context.Request.Method == "HEAD" && context.Request.Headers[RequestHeader].FirstOrDefault() == "N")
            {
                context.Response.Headers.Add(ResponseHeader, "No");
                // See you on the next request.
                //Program.Shutdown();
            }
            else
            {
                await _next(context);
            }
        }
    }
}
